'use strict';

const BaseController = require('../../core/base_controller');

class CollectController extends BaseController {
  // 添加收藏
  async create() {
    const { ctx } = this;
    const { collect_id, type } = ctx.request.body;
    const { user_id } = ctx.headers; // 从token中获取用户id

    // 参数验证
    const rules = {
      collect_id: { type: 'integer', required: true },
      type: { 
        type: 'enum', 
        values: ['forum', 'job'], 
        required: true 
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    // 检查是否已收藏
    const exist = await ctx.model.UserCollect.findOne({
      where: {
        user_id,
        collect_id,
        type
      }
    });

    if (exist) {
      ctx.throw(400, '已经收藏过了');
    }

    // 检查收藏对象是否存在
    let target;
    if (type === 'forum') {
      target = await ctx.model.Forum.findByPk(collect_id);
    } else if (type === 'job') {
      target = await ctx.model.JobOpening.findByPk(collect_id);
    }

    if (!target) {
      ctx.throw(404, '收藏对象不存在');
    }

    // 创建收藏记录
    const collect = await ctx.model.UserCollect.create({
      user_id,
      collect_id,
      type
    });

    // 更新收藏数
    if (type === 'forum') {
      await target.increment('collect_num');
    }

    this.success(collect);
  }

  // 取消收藏
  async destroy() {
    const { ctx } = this;
    const { collect_id, type } = ctx.request.body;
    const { user_id } = ctx.headers;

    // 参数验证
    const rules = {
      collect_id: { type: 'integer', required: true },
      type: { 
        type: 'enum', 
        values: ['forum', 'job'], 
        required: true 
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    // 查找收藏记录
    const collect = await ctx.model.UserCollect.findOne({
      where: {
        user_id,
        collect_id,
        type
      }
    });

    if (!collect) {
      ctx.throw(404, '收藏记录不存在');
    }

    // 删除收藏记录
    await collect.destroy();

    // 更新收藏数
    if (type === 'forum') {
      const forum = await ctx.model.Forum.findByPk(collect_id);
      if (forum) {
        await forum.decrement('collect_num');
      }
    }

    this.success(null, '取消收藏成功');
  }

  // 获取收藏状态
  async getStatus() {
    const { ctx } = this;
    const { collect_id, type } = ctx.query;
    const { user_id } = ctx.headers;

    // 参数验证
    const rules = {
      collect_id: { type: 'integer', required: true },
      type: { 
        type: 'enum', 
        values: ['forum', 'job'], 
        required: true 
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    // 查找收藏记录
    const collect = await ctx.model.UserCollect.findOne({
      where: {
        user_id,
        collect_id,
        type
      }
    });

    this.success({
      is_collected: !!collect
    });
  }
}

module.exports = CollectController; 